package org.dozer;

import java.util.ArrayList;
import java.util.List;
import java.util.TimerTask;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.seedwill.common.dozer.reloading.FileChangedReloadingStrategy;
import com.seedwill.common.dozer.reloading.FileConfiguration;

public class MappingChangeMonitor extends TimerTask {
	
	private static final Log log = LogFactory.getLog(MappingChangeMonitor.class);
	
	/**
	 * seedwill dozer
	 */
	private SeedWillChangeAwareDozerBeanMapper dozerMapperInstance;

	public SeedWillChangeAwareDozerBeanMapper getDozerMapperInstance() {
		return dozerMapperInstance;
	}

	public void setDozerMapperInstance(SeedWillChangeAwareDozerBeanMapper dozerMapperInstance) {
		this.dozerMapperInstance = dozerMapperInstance;
	}
	
	private List<FileConfiguration> mappingFilesConfig; // String file names

	public List<FileConfiguration> getMappingFilesConfig() {
		return mappingFilesConfig;
	}

	public void setMappingFilesConfig(List<FileConfiguration> mappingFilesConfig) {
		this.mappingFilesConfig = mappingFilesConfig;
	}
	
	/**
	 * 
	 */
	private synchronized void resetChecking() {
		if (this.mappingFilesConfig != null
				&& this.mappingFilesConfig.size() > 0) {
			for (FileConfiguration f : mappingFilesConfig) {
				if (f.getStrategy().reloadingRequired()) {
					f.getStrategy().reloadingPerformed();
				}
			}
		}
		log.info("reset DOZER");
	}
	
	/**
	 * @return
	 */
	private synchronized boolean changeChecking() {
		if (this.mappingFilesConfig != null
				&& this.mappingFilesConfig.size() > 0) {
			for (FileConfiguration f : mappingFilesConfig) {
				if (f.getStrategy().reloadingRequired()) {
					log.info("Dozer config file changed , need reset DOZER");
					return true;
				}
			}
		}
		return false;
	}
	
	/**
	 * init
	 */
	public void init() {
		if (dozerMapperInstance!=null && dozerMapperInstance.getMappingFiles() != null && dozerMapperInstance.getMappingFiles().size() > 0) {
			if(mappingFilesConfig == null) {
				mappingFilesConfig = new ArrayList<FileConfiguration>();
			}
			mappingFilesConfig.clear();
			for (String f : dozerMapperInstance.getMappingFiles()) {
				FileConfiguration config = new FileConfiguration(f);
				config.setReloadingStrategy(new FileChangedReloadingStrategy());
				mappingFilesConfig.add(config);
			}
		}
	}

	@Override
	public void run() {
		if(dozerMapperInstance!=null && changeChecking()) {
			dozerMapperInstance.reload();
			resetChecking();
		}
	}
	
}
